package com.example.testrecorder;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Process;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.testrecorder.adapter.IssueShowedAdapter;
import com.example.testrecorder.domain.Issue;
import com.example.testrecorder.domain.IssueShowed;
import com.example.testrecorder.domain.QueAndAns;
import com.example.testrecorder.domain.SelectIssueBean;
import com.example.testrecorder.domain.User;
import com.example.testrecorder.utils.ActivityCollector;
import com.example.testrecorder.utils.BitmapUtil;
import com.example.testrecorder.utils.DateUtil;
import com.example.testrecorder.utils.LogUtil;
import com.example.testrecorder.utils.MyDialog;
import com.example.testrecorder.utils.PermissionUtil;
import com.example.testrecorder.utils.ViewUtil;
import com.example.testrecorder.utils.WindowUtil;
import com.example.testrecorder.view.MyPopupWindow;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;

import org.litepal.LitePal;
import org.litepal.crud.LitePalSupport;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

public class MainActivity extends BaseActivity implements View.OnClickListener{
    Toolbar toolbar;
    private EditText searchEt;
    private DrawerLayout drawerLayout;
    private NavigationView navigationView;
    private RelativeLayout headerView;
    private CircleImageView circleImageView;
    private RecyclerView rv;
    private FloatingActionButton addBtn;
    private SwipeRefreshLayout sRl;
    private IssueShowedAdapter issueShowedAdapter;
    private ArrayList<IssueShowed> arrayList;
    private LinearLayout topLl,platformLl,frequencyLl,severityLl,solvedLl;
    private TextView platformTv,frequencyTv,severityTv,solvedTv;
    private ImageView platformIv,frequencyIv,severityIv,solvedIv,msgIv;
    private MyPopupWindow platformWindow,frequencyWindow,severityWindow,solvedWindow;
    private SelectIssueBean selectIssueBean=new SelectIssueBean();
    private User currUser=MyApplication.currUser;
    private TopLlResetReceiver resetReceiver;
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(MyApplication.currUser==null){//如果没有登录
            finish();
        }
        TextView trueNameTv = headerView.findViewById(R.id.trueNameTv);
        trueNameTv.setText(MyApplication.currUser.getTrueName());
        TextView emailTv = headerView.findViewById(R.id.emailTv);
        emailTv.setText(MyApplication.currUser.getEmail());
        resetReceiver=new TopLlResetReceiver();
        LocalBroadcastManager.getInstance(this).registerReceiver(resetReceiver,new IntentFilter("reset"));//注册广播接收器
        List<QueAndAns> list = LitePal.where("user_id=?", "" + currUser.getId()).find(QueAndAns.class);
        String tel = currUser.getTel();
        if(list.size()==3&&!TextUtils.isEmpty(tel)){//当前用户设置有3个密保问题，并且设置了手机号
            msgIv.setVisibility(View.GONE);
        }else {
            msgIv.setVisibility(View.VISIBLE);//没有设置有密保问题的话就展示警告图片
        }

        if(!TextUtils.isEmpty(currUser.getHeadPortraitStr())){
            circleImageView.setImageBitmap(BitmapUtil.getBitmapFromPath(currUser.getHeadPortraitStr()));
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(resetReceiver);//注销广播接收器
    }

    private void initView() {
        toolbar=findViewById(R.id.toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });
        toolbar.setNavigationIcon(R.drawable.ic_left_menu);
        View searchView = LayoutInflater.from(this).inflate(R.layout.search_ll, null);
        int screenWidth = WindowUtil.getScreenWidth(this);//屏幕的宽度
        int pxFromDp = WindowUtil.getPxFromDp(this, 120);
        int searchViewWidth=screenWidth-pxFromDp;
        toolbar.addView(searchView,searchViewWidth,80);
        solvedLl=findViewById(R.id.solvedLl);
        solvedLl.setOnClickListener(this);
        solvedTv=findViewById(R.id.solvedTv);
        solvedIv=findViewById(R.id.solvedIv);
        severityLl=findViewById(R.id.severityLl);
        severityLl.setOnClickListener(this);
        severityTv=findViewById(R.id.severityTv);
        severityIv=findViewById(R.id.severityIv);
        frequencyLl=findViewById(R.id.frequencyLl);
        frequencyLl.setOnClickListener(this);
        frequencyIv=findViewById(R.id.frequencyIv);
        frequencyTv=findViewById(R.id.frequencyTv);
        topLl=findViewById(R.id.topLl);
        platformLl=findViewById(R.id.platformLl);
        platformLl.setOnClickListener(this);
        platformTv=findViewById(R.id.platformTv);
        platformIv=findViewById(R.id.platformIv);
        sRl=findViewById(R.id.sRl);
        sRl.setColorSchemeColors(getResources().getColor(R.color.dark_blue));//设置进度条的颜色
        sRl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {//设置下拉刷新的监听
            @Override
            public void onRefresh() {
                arrayList.clear();//清空数据
                selectIssueBean=new SelectIssueBean();//重置查询参数
                List<Issue> all = LitePal.where("user_id=?",""+currUser.getId()).order("proposetime desc").find(Issue.class);//再次查询数据库
                for (int i = 0; i < all.size(); i++) {
                    Issue issue = all.get(i);
                    arrayList.add(new IssueShowed(issue.getId(),issue.getTitle(),issue.getContent(), DateUtil.getFormatDateStr(issue.getProposeTime()),issue.getSolved(),issue.getSeverity()));
                }
                issueShowedAdapter.notifyDataSetChanged();//更新列表数据
                sRl.setRefreshing(false);//停止刷新
                resetAllColor();//重置筛选栏的颜色状态
                resetTextAndPosition();
                searchEt.setText("");
                searchEt.clearFocus();
            }
        });
        addBtn=findViewById(R.id.bt_add);
        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,AddRecordActivity.class));
            }
        });
        rv=findViewById(R.id.rv);
        rv.setLayoutManager(new GridLayoutManager(this,2));
        arrayList=new ArrayList<>();
        List<Issue> all = LitePal.where("user_id=?",""+currUser.getId()).order("proposetime desc").find(Issue.class);
        for (int i = 0; i < all.size(); i++) {
            Issue issue = all.get(i);
            arrayList.add(new IssueShowed(issue.getId(),issue.getTitle(),issue.getContent(), DateUtil.getFormatDateStr(issue.getProposeTime()),issue.getSolved(),issue.getSeverity()));
        }
        issueShowedAdapter = new IssueShowedAdapter(arrayList,this);
        rv.setAdapter(issueShowedAdapter);
        navigationView=findViewById(R.id.nv);
        navigationView.setItemIconTintList(null);//解决部分菜单的图标显示不出来
        drawerLayout=findViewById(R.id.dl);
        searchEt=findViewById(R.id.searchEt);
        headerView = (RelativeLayout) navigationView.getHeaderView(0);
        msgIv=headerView.findViewById(R.id.msgIv);
        msgIv.setOnClickListener(this);
        circleImageView=headerView.findViewById(R.id.cv);
        circleImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,PersonalDataActivity.class));
            }
        });
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()){
                    case R.id.exit:
                        MyDialog myDialog=new MyDialog(MainActivity.this,Color.parseColor("#FFF4F8FB"));
                        myDialog.show();
                        myDialog.setContent("您确定要退出程序吗？");
                        myDialog.setOnPositiveListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                myDialog.dismiss();
                                ActivityCollector.getInstance().removeAll();
                                Process.killProcess(Process.myPid());//杀掉当前进程
                            }
                        });
                        myDialog.setOnNegativeListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                myDialog.dismiss();
                            }
                        });
                        break;
                    case R.id.logout:
                        MyDialog myDialog2=new MyDialog(MainActivity.this,Color.parseColor("#FFF4F8FB"));
                        myDialog2.show();
                        myDialog2.setContent("您确定要注销登陆吗？");
                        myDialog2.setOnPositiveListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                myDialog2.dismiss();
                                MyApplication.currUser=null;
                                startActivity(new Intent(MainActivity.this,LoginActivity.class));//跳到登录界面
                            }
                        });
                        myDialog2.setOnNegativeListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                myDialog2.dismiss();
                            }
                        });
                        break;
                    case R.id.setting:
                        startActivity(new Intent(MainActivity.this,SettingActivity.class));
                        break;
                    case R.id.feedback:
                        startActivity(new Intent(MainActivity.this,FeedbackActivity.class));
                        break;
                    case R.id.personalData:
                        startActivity(new Intent(MainActivity.this,PersonalDataActivity.class));
                        break;
                    default:
                }
                return true;
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){

            case R.id.platformLl:
                LogUtil.logD(TAG,"platformLl被点击了……");
                changeTvColor(platformTv,platformIv);
                ArrayList<String> platformList = new ArrayList<>();
                platformList.add("全部平台");
                platformList.add("IOS");
                platformList.add("Android");
                if(platformWindow==null){//空的话才会创建实例
                    platformWindow=new MyPopupWindow(MainActivity.this, platformList, new MyPopupWindow.OnItemClickCallBack() {
                        @Override
                        public void click(String itemStr, int itemPosition) {
                            platformTv.setText(itemStr);
                            if(itemPosition==0){
                                selectIssueBean.setPlatform("IOS和Android");
                            }else {
                                selectIssueBean.setPlatform(platformList.get(itemPosition));
                            }
                            selectIssue(selectIssueBean,platformWindow);

                        }
                    });
                }
                if(!platformWindow.isShowing()){
                    platformWindow.showAsDropDown(topLl);
                }
                break;
            case R.id.frequencyLl:
                changeTvColor(frequencyTv,frequencyIv);
                ArrayList<String> frequencyList = new ArrayList<>();
                frequencyList.add("全部频率");
                frequencyList.add("高频");
                frequencyList.add("中频");
                frequencyList.add("低频");
                if(frequencyWindow==null){//空的话才会创建实例
                    frequencyWindow=new MyPopupWindow(MainActivity.this, frequencyList, new MyPopupWindow.OnItemClickCallBack() {
                        @Override
                        public void click(String itemStr, int itemPosition) {
                            frequencyTv.setText(itemStr);
                            if(itemPosition==0){
                                selectIssueBean.setFrequency(null);
                            }else if(itemPosition==1){
                                selectIssueBean.setFrequency("高");
                            }else if(itemPosition==2){
                                selectIssueBean.setFrequency("中");
                            }else if(itemPosition==3){
                                selectIssueBean.setFrequency("低");
                            }
                            selectIssue(selectIssueBean,frequencyWindow);

                        }
                    });
                }
                if(!frequencyWindow.isShowing()){
                    frequencyWindow.showAsDropDown(topLl);
                }
                break;
            case R.id.severityLl:
                changeTvColor(severityTv,severityIv);
                ArrayList<String> severityList = new ArrayList<>();
                severityList.add("全部程度");
                severityList.add("严重");
                severityList.add("一般");
                severityList.add("轻微");
                if(severityWindow==null){//空的话才会创建实例
                    severityWindow=new MyPopupWindow(MainActivity.this, severityList, new MyPopupWindow.OnItemClickCallBack() {
                        @Override
                        public void click(String itemStr, int itemPosition) {
                            severityTv.setText(itemStr);
                            if(itemPosition==0){
                                selectIssueBean.setSeverity(null);
                            }else if(itemPosition==1){
                                selectIssueBean.setSeverity("高");
                            }else if(itemPosition==2){
                                selectIssueBean.setSeverity("中");
                            }else if(itemPosition==3){
                                selectIssueBean.setSeverity("低");
                            }
                            selectIssue(selectIssueBean,severityWindow);
                        }
                    });
                }
                if(!severityWindow.isShowing()){
                    severityWindow.showAsDropDown(topLl);
                }
                break;
            case R.id.solvedLl:
                changeTvColor(solvedTv,solvedIv);
                ArrayList<String> solvedList = new ArrayList<>();
                solvedList.add("全部状态");
                solvedList.add("已解决");
                solvedList.add("未解决");
                solvedList.add("无需解决");
                if(solvedWindow==null){//空的话才会创建实例
                    solvedWindow=new MyPopupWindow(MainActivity.this, solvedList, new MyPopupWindow.OnItemClickCallBack() {
                        @Override
                        public void click(String itemStr, int itemPosition) {
                            solvedTv.setText(itemStr);
                            if(itemPosition==0){
                                selectIssueBean.setSolved(null);
                            }else{
                                selectIssueBean.setSolved(solvedList.get(itemPosition));
                            }
                            selectIssue(selectIssueBean,solvedWindow);
                        }
                    });
                }
                if(!solvedWindow.isShowing()){
                    solvedWindow.showAsDropDown(topLl);
                }
                break;
            case R.id.msgIv:
                MyDialog myDialog=new MyDialog(MainActivity.this,Color.parseColor("#f4f8fb"));
                myDialog.setTitle("警告");
                myDialog.setContent("您未设置手机号或密保问题，忘记密码后将难以找回密码，请您前往“个人资料”页面设置您的手机号和密保问题。");
                myDialog.setTitleTextColor("#ff0000");
                myDialog.setNegativeBtnVisibility(false);
                myDialog.setMiddleLineVisibility(false);
                myDialog.show();
                myDialog.setOnPositiveListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myDialog.dismiss();
                    }
                });
                break;
            default:
        }
    }

    /**
     * 根据条件从数据库中筛选测试问题
     * @param selectIssueBean
     */
    private void selectIssue(SelectIssueBean selectIssueBean,MyPopupWindow myPopupWindow) {
        String searchStr = searchEt.getText().toString();
        if(!TextUtils.isEmpty(searchStr)){
            selectIssueBean.setKeyword(searchStr);
        }
        String platform = selectIssueBean.getPlatform();
        String frequency = selectIssueBean.getFrequency();
        String severity = selectIssueBean.getSeverity();
        String solved = selectIssueBean.getSolved();
        StringBuilder sb=new StringBuilder("user_id="+currUser.getId()+" ");//动态查询条件
        if(platform!=null){
            sb.append("and platform='"+platform+"' ");
        }
        if(frequency!=null){
            sb.append("and frequency='"+frequency+"' ");
        }
        if(severity!=null){
            sb.append("and severity='"+severity+"' ");
        }
        if(solved!=null){
            sb.append("and solved='"+solved+"' ");
        }
        if(selectIssueBean.getKeyword()!=null){
            sb.append("and (title like '%"+selectIssueBean.getKeyword()+"%' or content like '%"+selectIssueBean.getKeyword()+"%') ");
        }
        String sql="select * from issue where "+sb.toString();
        LogUtil.logD(TAG,sql);
        LogUtil.logD(TAG,selectIssueBean.toString());
        Cursor cursor = LitePal.findBySQL(sql);
        arrayList.clear();
        while (cursor.moveToNext()){
            int id = cursor.getInt(cursor.getColumnIndex("id"));
            String title = cursor.getString(cursor.getColumnIndex("title"));
            String content = cursor.getString(cursor.getColumnIndex("content"));
            String sol = cursor.getString(cursor.getColumnIndex("solved"));
            String sev = cursor.getString(cursor.getColumnIndex("severity"));
            long proposeTime = cursor.getLong(cursor.getColumnIndex("proposetime"));//注意大小写，SQLite对大小写比较敏感
            arrayList.add(new IssueShowed(id,title,content,DateUtil.getFormatDateStr(new Date(proposeTime)),sol,sev));
        }
        issueShowedAdapter.notifyDataSetChanged();
        myPopupWindow.dismiss();
    }

    private void changeTvColor(TextView targetTv,ImageView imageView) {
        //先重置所有TextView、ImageView的颜色状态
        resetAllColor();
        //再针对当前的TextView、ImageView设置颜色，替换图片
        targetTv.setTextColor(Color.parseColor("#5185CA"));
        imageView.setImageResource(R.drawable.ic_expand_more_blue);
    }

    private void resetAllColor() {
        platformTv.setTextColor(Color.parseColor("#FF666666"));
        frequencyTv.setTextColor(Color.parseColor("#FF666666"));
        severityTv.setTextColor(Color.parseColor("#FF666666"));
        solvedTv.setTextColor(Color.parseColor("#FF666666"));
        platformIv.setImageResource(R.drawable.ic_expand_more_gray);
        frequencyIv.setImageResource(R.drawable.ic_expand_more_gray);
        severityIv.setImageResource(R.drawable.ic_expand_more_gray);
        solvedIv.setImageResource(R.drawable.ic_expand_more_gray);
    }

    private void resetTextAndPosition(){
        platformTv.setText("全部平台");
        frequencyTv.setText("全部频率");
        severityTv.setText("全部程度");
        solvedTv.setText("全部状态");
        if(platformWindow!=null){
            platformWindow.selectedPosition=-1;
        }
        if(frequencyWindow!=null){
            frequencyWindow.selectedPosition=-1;
        }
        if(severityWindow!=null){
            severityWindow.selectedPosition=-1;
        }
        if(solvedWindow!=null){
            solvedWindow.selectedPosition=-1;
        }
    }

    /**
     * 重置顶部筛选栏的广播接收器
     */
    private class TopLlResetReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            resetAllColor();
            resetTextAndPosition();
            selectIssueBean=new SelectIssueBean();//重置查询参数
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();
        if(itemId==R.id.search){
            String keyword = searchEt.getText().toString();
            LocalBroadcastManager.getInstance(MainActivity.this).sendBroadcast(new Intent("reset"));
            selectIssueBean.setKeyword(keyword);

            arrayList.clear();//清空数据
            List<Issue> all = LitePal.where("user_id=? and (title like '%"+keyword+"%' or content like '%"+keyword+"%')",""+currUser.getId()).order("proposetime desc").find(Issue.class);//再次查询数据库
            LogUtil.logD(TAG,"搜索列表的大小是"+all.size());
            if(all.size()==0){
                MyDialog .showInfo(MainActivity.this,"暂无相关记录！");
            }
            for (int i = 0; i < all.size(); i++) {
                Issue issue = all.get(i);
                arrayList.add(new IssueShowed(issue.getId(),issue.getTitle(),issue.getContent(), DateUtil.getFormatDateStr(issue.getProposeTime()),issue.getSolved(),issue.getSeverity()));
            }
            issueShowedAdapter.notifyDataSetChanged();
            //ViewUtil.hideAllInputMethod(MainActivity.this);
            ViewUtil.hideOneInputMethod(MainActivity.this,toolbar);
        }
        return true;
    }
}